package com.zhejiangzhengyuan.municipal_common.service.impl;

import com.zhejiangzhengyuan.municipal_common.entity.File;
import com.zhejiangzhengyuan.municipal_common.mapper.FileMapper;
import com.zhejiangzhengyuan.municipal_common.service.FileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhejiangzhengyuan.municipal_common.utils.excelFileUtils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

import static com.zhejiangzhengyuan.municipal_common.utils.excelFileUtils.FileUtil.getFilePo;

/**
 * 文件表，目前将文件数据单独列为一个数据库进行处理，目的是为了可能出现的情况（单独的文件中心，文件存储拓展） 服务实现类
 *
 * @author linju
 * @since 2019-11-22
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {
  @Autowired private FileMapper fileMapper;

  @Override
  public void removeFileById(Long fileId) throws IOException {
    File file = fileMapper.selectById(fileId);
    if (Objects.nonNull(file)) {
      String link = file.getLink();
      FileUtil.removeFile(link);
      fileMapper.deleteById(fileId);
    }
  }

  @Override
  public File saveFile(String moduleName, MultipartFile file) throws IOException {
      File result = getFilePo(null, moduleName, file);
      fileMapper.insert(result);
    return result;
  }
}
